package com.ccp.dev.form.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.engine.GroovyScriptEngine;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.model.SysScript;
import com.ccp.dev.form.service.SysScriptService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 脚本管理 控制器类
 *
 * @author zhaowj
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_FORM + "/script")
@Action(ownermodel = SysAuditModelType.PROCESS_AUXILIARY)
public class SysScriptController extends SysBaseController {
    @Resource
    private SysScriptService sysScriptService;


    /**
     * 脚本列表
     *
     * @return JSON列表数据
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "查询脚本列表", exectype = "查询日志",
            detail = "查询脚本列表<#if success>成功<#else>失败</#if>")
    public Object getScripts() {
        List<SysScript> list;
        try {
            list = sysScriptService.queryListALL();
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            e.printStackTrace();
            return getResultDataError("query.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(list);
    }

    /**
     * 验证expression中的脚本
     *
     * @param request 请求
     * @return 验证结果
     */
    @RequestMapping("/getValidateResult")
    @ResponseBody
    @Action(description = "验证expression中的脚本", exectype = "查询日志",
            detail = "验证expression中的脚本<#if success>成功<#else>失败</#if>")
    public ResultData getValidateResult(HttpServletRequest request) {
        String script = RequestUtil.getString(request, "script");
        GroovyScriptEngine engine = AppUtil.getBean(GroovyScriptEngine.class);
        Map<String, Object> reObj = new HashMap<>(16);
        try {
            Object result = engine.executeObject(script, null);
            if (result != null) {
                reObj.put("result", result);
                reObj.put("resultType", result.getClass().getName());
            }
        } catch (Exception ex) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("script.verify.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("script.verify.success", reObj);
    }

    /**
     * 跳转脚本管理分页列表
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/scriptList")
    @Action(description = "跳转脚本管理分页列表", exectype = "页面跳转日志")
    public String sysScriptView() {
        return getAutoView();
    }

    /**
     * 跳转脚本管理导入页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转脚本管理导入页面", exectype = "页面跳转日志")
    public String importView() {
        return getAutoView();
    }

    /**
     * 查询脚本分类列表
     *
     * @return ResultData
     */
    @RequestMapping("/queryCategoryList")
    @ResponseBody
    @Action(description = "查询脚本分类列表", exectype = "查询日志",
            detail = "查询脚本分类列表<#if success>成功<#else>失败</#if>")
    public ResultData queryCategoryList() {
        List<String> categoryList;
        try {
            categoryList = sysScriptService.getDistinctCategory();
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("query.success", categoryList);
    }

    /**
     * 取得脚本管理分页列表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/scriptList")
    @ResponseBody
    @Action(description = "查看脚本管理分页列表", exectype = "查询日志",
            detail = "查看脚本管理分页列表<#if success>成功<#else>失败</#if>")
    public ResultData list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request);
        List<SysScript> sysScriptList;
        try {
            sysScriptList = sysScriptService.queryListALL(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", queryFilter.getPageBean().getTotalCount(), sysScriptList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 跳转添加或编辑脚本管理页面
     *
     * @return
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/scriptEdit")
    @Action(description = "添加或编辑脚本管理页面跳转", exectype = "页面跳转日志")
    public String scriptEdit(HttpServletRequest request, Model model) {
        String id = RequestUtil.getString(request, "id");
        List<String> categoryList = sysScriptService.getDistinctCategory();
        if (StringUtil.isNotEmpty(id)) {
            SysScript sysScript = sysScriptService.getOneById(id);
            model.addAttribute("sysScript", sysScript);
        }
        model.addAttribute("id", id).addAttribute("categoryList", categoryList);
        return getAutoView();
    }

    /**
     * 添加或更新脚本管理。
     *
     * @param sysScript 添加或更新的实体
     * @return
     * @throws Exception
     */
    @RequestMapping("/save")
    @ResponseBody
    @Action(description = "添加或更新脚本管理", exectype = "添加或更新日志",
            detail = "添加或更新脚本管理<#if success>成功<#else>失败</#if>")
    public ResultData save(SysScript sysScript) {
        if (StringUtil.isEmpty(sysScript.getId())) {
            List<SysScript> rtn = sysScriptService.getByName(sysScript.getName());
            if (rtn != null && rtn.size() > 0) {
                return getResultDataError("script.verify.repeat");
            } else {
                sysScript.setId(UUIDUtils.getUUIDFor32());
                try {
                    sysScriptService.add(sysScript);
                    SysAuditThreadLocalHolder.putParamerter("success", true);
                    return getResultDataSuccess("save.success");
                } catch (Exception e) {
                    SysAuditThreadLocalHolder.putParamerter("success", false);
                    return getResultDataError("save.failure");
                }
            }
        } else {
            try {
                sysScriptService.update(sysScript);
                SysAuditThreadLocalHolder.putParamerter("success", true);
                return getResultDataSuccess("update.success");
            } catch (Exception e) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return getResultDataError("update.failure");
            }
        }
    }

    /**
     * 删除脚本管理
     *
     * @param request
     */
    @RequestMapping("/del")
    @ResponseBody
    @Action(description = "删除脚本", exectype = "删除日志",
            detail = "删除脚本<#if success>成功<#else>失败</#if>")
    public ResultData del(HttpServletRequest request) {
        try {
            String[] lAryId = RequestUtil.getStringAryByStr(request, "id");
            sysScriptService.delByIds(lAryId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("delete.success");
        } catch (Exception ex) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 导出脚本
     *
     * @param request
     */
    @RequestMapping("/export")
    @Action(description = "导出脚本", exectype = "导出日志",
            detail = "导出脚本<#if success>成功<#else>失败</#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        String fileName;
        String strXml;
        String[] lAryId = RequestUtil.getStringAryByStr(request, "ids");
        List<SysScript> list = sysScriptService.queryListALL(null);
        try {
            if (BeanUtils.isEmpty(lAryId)) {
                strXml = sysScriptService.exportXml(list);
                fileName = "全部脚本_" + DateFormatUtil.getNowByString("yyyyMMddHHmmdd") + ".xml";
            } else {
                strXml = sysScriptService.exportXml(lAryId);
                fileName = DateFormatUtil.getNowByString("yyyyMMddHHmmdd") + ".xml";
                if (lAryId.length == 1) {
                    SysScript sysScript = sysScriptService.getOneById(lAryId[0]);
                    fileName = sysScript.getName() + "_" + fileName;
                } else if (lAryId.length == list.size()) {
                    fileName = "全部脚本_" + fileName;
                } else {
                    fileName = "多条脚本_" + fileName;
                }
            }
            FileUtil.downLoad(request, response, strXml, fileName);
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
    }

    /**
     * 导入系统模板XML页面跳转。
     *
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/importXml")
    @Action(description = "导入系统模板XML页面跳转", exectype = "页面跳转日志")
    public String importXmlView() {
        return getAutoView();
    }

    /**
     * 导入脚本
     *
     * @param request
     */
    @RequestMapping("/importXml")
    @ResponseBody
    @Action(description = "导入脚本", exectype = "导入日志",
            detail = "导入脚本<#if success>成功<#else>失败</#if>")
    public ResultData importXml(MultipartHttpServletRequest request) {
        MultipartFile fileLoad = request.getFile("file");
        try {
            sysScriptService.importXml(fileLoad.getInputStream());
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("file.importXml.success");
        } catch (Exception ex) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("file.importXml.failure", 1, ex.getMessage());
        }
    }

    /**
     * 检查脚本的名称有没有重复
     * @param request
     * @return 返回结果
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/checkRepeatName")
    @Action(description="检查脚本的名称有没有重复",detail = "脚本的名称<#if success>可以使用<#else>已经存在</#if>")
    @ResponseBody
    public ResultData checkRepeatName(HttpServletRequest request) {
        String id=RequestUtil.getString(request, "id", "");
        String name=RequestUtil.getString(request, "name", "");
        //名称是否为空
        if("".equals(name)){
            return getResultDataError("script.name.null");
        }else{
            boolean isRepeatName = sysScriptService.checkRepeatName(id,name);
            //名称是否已存在
            if(isRepeatName){
                SysAuditThreadLocalHolder.putParamerter("success",true);
                return getResultDataSuccess("script.name.success");
            }else{
                SysAuditThreadLocalHolder.putParamerter("success",false);
                return getResultDataError("script.name.failure");
            }
        }
    }
}
